package main

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"time"
)

type User struct {
	gorm.Model
	//Id           int64  `gorm:"primary"`
	Name         string `gorm:"type:varchar(50);column:name"`
	Age          uint8
	Phone        string `valid:"matches(^1[3-9]{1}\\d{9}$)"`
	Address      string
	Email        string
	LoginOutTime time.Time
}

func main() {
	db, connErr := gorm.Open("mysql", "root:123456@(localhost:3306)/dqm?charset=utf8&parseTime=True&loc=Local")
	if connErr != nil {
		panic("failed to connect database")
	}
	defer func(db *gorm.DB) {
		err := db.Close()
		if err != nil {
			panic("failed to close database")
		}
	}(db)
	db.SingularTable(true) // gorm会在创建表的时候去掉”s“的后缀
	fmt.Printf("连接测试成功 %T %v\n", db, db.Value)
	//db.AutoMigrate(&User{}) // 自动创建数据表及字段
	// 查询
	var queryRow User
	db.Where("id = ? ", 6).Find(&queryRow)
	if queryRow.ID > 0 {
		fmt.Printf("查询到Id=1的数据：%T,%v\n", queryRow, queryRow)
	} else {
		zhangsan := &User{Model: gorm.Model{ID: 1, CreatedAt: time.Now(), UpdatedAt: time.Now()},
			Name: "zhangsan", Age: 12, Phone: "13581619396", Address: "山东菏泽", Email: "pzhang@rxhui.com", LoginOutTime: time.Now()}
		db.Create(zhangsan) // 增加
		return
	}
	// 修改
	db.Model(&queryRow).Update("name", "Lisi")
	// 创建
	//queryRow.ID = 4
	//db.Create(&queryRow)
	// 删除
	var userToDelete User
	db.Where("id = ?", int64(6)).First(&userToDelete)
	if userToDelete.ID > 0 {
		result := db.Delete(&userToDelete)
		if result.Error != nil {
			// 处理删除错误
			fmt.Println("删除用户失败:", result.Error)
		} else {
			fmt.Println("删除用户成功")
		}
	} else {
		fmt.Println("未找到id为6的用户")
	}
}
